// 加载分页模块
let laypage = layui.laypage;
let form = layui.form;

//获取文章的请求参数
let data = {
    pagenum: 1,
    pagesize: 2,
}

// 获取文章列表，渲染
function renderArticle() {
    $.ajax({
        url: '/my/article/list',
        data: data,
        success: function(res) {
            // console.log(res)
            let arr = [];
            res.data.forEach(item => {
                arr.push(`<tr>
        <td>${item.title}</td>
        <td>${item.cate_name}</td>
        <td>${item.pub_date}</td>
        <td>${item.state}</td>
        <td>
          <a href="./edit.html?id=${item.id}" class="layui-btn layui-btn-xs">编辑</a>
          <button type="button" class="layui-btn layui-btn-danger layui-btn-xs">删除</button>
        </td>
      </tr>`);
            });
            $('tbody').html(arr.join(""));
            showPage(res.total);
        }
    });
}

renderArticle();

// 分页
function showPage(t) {
    laypage.render({
        elem: 'page',
        count: t,
        limit: data.pagesize,
        curr: data.pagenum,

        limits: [2, 3, 5, 10],
        layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],

        jump: function(obj, first) {

            if (!first) {
                data.pagenum = obj.curr;
                data.pagesize = obj.limit;
                renderArticle();
            }
        }
    });
}


//筛选
// 获取所有的分类，渲染到 下拉框的位置
$.ajax({
    url: '/my/category/list',
    success: function(res) {
        let arr = [];
        res.data.forEach(item => {
            arr.push(`<option value="${item.id}">${item.name}</option>`)
        });
        $('select[name=category]').append(arr.join(''));
        // 更新渲染
        form.render('select');
    }
});

// 完成筛选
$('#search').on('submit', function(e) {
    e.preventDefault();
    let state = $('select[name=state]').val();
    let cate_id = $('select[name=category]').val();
    // console.log(cate_id, state);
    if (state) {
        data.state = state;
    } else {
        delete data.state;
    }

    if (cate_id) {
        data.cate_id = cate_id;
    } else {
        delete data.cate_id;
    }

    // 重置页码为 1
    data.pagenum = 1;

    renderArticle();
})